// 密码验证器UI交互逻辑
document.addEventListener('DOMContentLoaded', function() {
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const validateBtn = document.getElementById('validateBtn');
    const suggestBtn = document.getElementById('suggestBtn');
    const resultDiv = document.getElementById('result');
    const strengthMeter = document.getElementById('strengthMeter');

    // 验证密码并显示结果
    function validateAndShowResult() {
        const username = usernameInput.value;
        const password = passwordInput.value;
        
        const result = validatePassword(password, username);
        
        resultDiv.style.display = 'block';
        resultDiv.className = 'result ' + (result.isValid ? 'valid' : 'invalid');
        resultDiv.innerHTML = `
            <strong>${result.message}</strong>
            ${result.suggestion ? `<p>${result.suggestion}</p>` : ''}
        `;
        
        updateStrengthMeter(password);
    }

    // 更新密码强度指示器
    function updateStrengthMeter(password) {
        let strength = 0;
        
        // 长度检查
        if (password.length >= 8) strength += 25;
        if (password.length >= 12) strength += 15;
        
        // 复杂度检查
        if (/[A-Z]/.test(password)) strength += 15;
        if (/[a-z]/.test(password)) strength += 15;
        if (/\d/.test(password)) strength += 15;
        if (/[^A-Za-z0-9]/.test(password)) strength += 15;
        
        strength = Math.min(strength, 100);
        
        strengthMeter.style.width = strength + '%';
        strengthMeter.style.backgroundColor = 
            strength < 40 ? '#ff4d4d' :
            strength < 70 ? '#ffa64d' : '#4CAF50';
    }

    // 获取建议密码
    function getSuggestedPassword() {
        const suggestion = generateSuggestion();
        passwordInput.value = suggestion;
        validateAndShowResult();
    }

    // 事件监听
    validateBtn.addEventListener('click', validateAndShowResult);
    suggestBtn.addEventListener('click', getSuggestedPassword);
    
    // 实时验证（防抖处理）
    let debounceTimer;
    passwordInput.addEventListener('input', function() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            updateStrengthMeter(passwordInput.value);
        }, 300);
    });
});
